//
//  InfoCertificationViewController.m
//  JimiPay
//
//  Created by yull on 16/1/9.
//  Copyright (c) 2016年 com.shengyun. All rights reserved.
//

#import "InfoCertificationViewController.h"
#import "InfoCertificationCell.h"
#import "InfoCertificationHeaderView.h"
#import "TDProvince.h"
#import "TDSelectLocationTableViewController.h"
#import "TDSelectBankNameTableViewController.h"

#import "UITextField+BlocksKit.h"

@interface InfoCertificationViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate>

@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *placeholderArray;

@property (nonatomic, strong) NSString *IDCardFrontImage;
@property (nonatomic, strong) NSString *IDCardBackImage;
@property (nonatomic, strong) NSString *BankCardFrontImage;
@property (nonatomic, strong) NSString *IDCardAndBankCardImage;
@property (nonatomic, strong) NSString *activeCode;
@property (nonatomic, strong) NSString *realName;
@property (nonatomic, strong) NSString *IDNumber;
@property (nonatomic, strong) NSString *cardNo;
@property (nonatomic, strong) NSString *cardName;
@property (nonatomic, strong) TDProvince *province;
@property (nonatomic, strong) TDCity *city;
@property (nonatomic, strong) TDArea *area;

@property (nonatomic, strong) UIButton *currentPicB;

@end

@implementation InfoCertificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"信息认证";
    [self setupCustomBackItem];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"InfoCertificationCell" bundle:nil] forCellReuseIdentifier:@"InfoCertificationCell"];
    self.tableView.tableFooterView = [[UIView alloc] init];

    InfoCertificationHeaderView *headerView = [[NSBundle mainBundle] loadNibNamed:@"InfoCertificationHeaderView" owner:nil options:nil].firstObject;
    CGSize size = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    headerView.frame = CGRectMake(0, 0, size.width, size.height);
    headerView.ButtonAction = ^(UIButton *sender) {
        [self getPhoto:sender];
    };
    self.tableView.tableHeaderView = headerView;
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, CGRectGetWidth(self.tableView.frame), 80)];
    footerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    UIButton *commitB = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    commitB.frame = CGRectMake(10, 16, CGRectGetWidth(self.tableView.frame) - 20, 44);
    commitB.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    commitB.backgroundColor = MainColor;
    [commitB setTitle:@"提交审核" forState:0];
    [commitB setTitleColor:[UIColor whiteColor] forState:0];
    commitB.layer.cornerRadius = 5;
    commitB.layer.masksToBounds = YES;
    [commitB addTarget:self action:@selector(button_commit:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:commitB];
    
    self.tableView.tableFooterView = footerView;
    
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

#if SHOW_WEIZHUAN == 1
    self.titleArray = @[@"真实姓名",
                        @"身份证号",
                        @"开户行",
                        @"收款银行卡",
                        @"开户城市"];
    self.placeholderArray = @[@"请输入身份证上的姓名",
                              @"请输入身份证号",
                              @"请选择开户行",
                              @"请输入储蓄卡号（非信用卡）",
                              @"请选择（省 市/区）"];
#else 
    self.titleArray = @[@"激活码",
                        @"真实姓名",
                        @"身份证号",
                        @"开户行",
                        @"收款银行卡",
                        @"开户城市"];
    self.placeholderArray = @[@"请输入激活码",
                              @"请输入身份证上的姓名",
                              @"请输入身份证号",
                              @"请选择开户行",
                              @"请输入储蓄卡号（非信用卡）",
                              @"请选择（省 市/区）"];
#endif
}

- (void)setupCustomBackItem {
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_top_icon3"] style:UIBarButtonItemStyleDone target:self action:@selector(popViewController)];
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)popViewController {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)button_commit:(id)sender {
    
    [self.view endEditing:YES];
    
    if (!self.IDCardAndBankCardImage.length) {
        [self.navigationController.view makeToast:@"请拍摄手持身份证正面照" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.IDCardFrontImage.length) {
        [self.navigationController.view makeToast:@"请拍摄身份证正面照" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.IDCardBackImage.length) {
        [self.navigationController.view makeToast:@"请拍摄身份证反面照" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.BankCardFrontImage.length) {
        [self.navigationController.view makeToast:@"请拍摄银行卡正面照" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.realName.length) {
        [self.navigationController.view makeToast:@"请输入真实姓名" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.IDNumber.length) {
        [self.navigationController.view makeToast:@"请输入身份证号" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.province || !self.city || !self.area) {
        [self.navigationController.view makeToast:@"请选择开户城市" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.cardNo.length) {
        [self.navigationController.view makeToast:@"请输入储蓄卡号" duration:2.0f position:@"center"];
        return;
    }
    
    if (!self.cardName.length) {
        [self.navigationController.view makeToast:@"请选择银行名称" duration:2.0f position:@"center"];
        return;
    }
    
#if SHOW_WEIZHUAN == 1
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{@"custId":[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID],
                                                                                  @"custMobile":[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE],
                                                                                  @"cardHandheld":self.IDCardAndBankCardImage,
                                                                                  @"cardFront":self.IDCardFrontImage,
                                                                                  @"cardBack":self.IDCardBackImage,
                                                                                  @"bankFront":self.BankCardFrontImage,
                                                                                  @"custName":self.realName,
                                                                                  @"certificateNo":self.IDNumber,
                                                                                  @"provinceId":self.province.provId,
                                                                                  @"cityId":self.city.cityId,
                                                                                  @"regionId":self.area.areaId,
                                                                                  @"bankCode":self.area.bankcode,
                                                                                  @"cardNo":self.cardNo,
                                                                                  @"bankType":self.cardName}];
#else
    if (!self.activeCode.length) {
        [self.navigationController.view makeToast:@"请选择激活码" duration:2.0f position:@"center"];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{@"custId":[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID],
                                                                                  @"custMobile":[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE],
                                                                                  @"cardHandheld":self.IDCardAndBankCardImage,
                                                                                  @"cardFront":self.IDCardFrontImage,
                                                                                  @"cardBack":self.IDCardBackImage,
                                                                                  @"bankFront":self.BankCardFrontImage,
                                                                                  @"custName":self.realName,
                                                                                  @"certificateNo":self.IDNumber,
                                                                                  @"provinceId":self.province.provId,
                                                                                  @"cityId":self.city.cityId,
                                                                                  @"regionId":self.area.areaId,
                                                                                  @"bankCode":self.area.bankcode,
                                                                                  @"cardNo":self.cardNo,
                                                                                  @"bankType":self.cardName,
                                                                                  @"activeCode":self.activeCode}];
#endif
    
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [TDHttpEngine requestFor_REALNAME_CERT_WithDic:params complete:^(BOOL succeed, NSString *msg, id reqBody) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if (succeed) {
            
            NSString *key = [NSString stringWithFormat:@"cer-%@", [[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]];
            [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:key];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [TDUser defaultUser].cardBundingStatus = @"1";
            [TDUser defaultUser].custStatus = @"1";
            [self.navigationController.view makeToast:msg duration:2.0f position:@"center"];
            [self performSelector:@selector(popToRoot) withObject:self afterDelay:2.0f];
        } else {
            [self.navigationController.view makeToast:msg duration:2.0f position:@"center"];
        }
    }];
}

- (void)popToRoot
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)getPhoto:(UIButton *)sender
{
    self.currentPicB = sender;
    
#if !SIMULATOR
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType =UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
    else{
        [self.view makeToast:@"该设备没有摄像头" duration:2.0f position:@"center"];
    }
#else
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePicker animated:YES completion:nil];
#endif
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"照片信息--%@", info);
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    while (imageData.length > 200*1024) {
        image = [self scaleImage:image toScale:0.5];
        imageData = UIImageJPEGRepresentation(image, 0.5);
    }
    
    [self.currentPicB setBackgroundImage:image forState:0];
    switch (self.currentPicB.tag) {
        case IDCardFrontBTag:{
            self.IDCardFrontImage = [imageData base64EncodedString];
//            self.IDCardFrontImage = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        }
            break;
        case IDCardBackBTag:{
            self.IDCardBackImage = [imageData base64EncodedString];
//            self.IDCardBackImage = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        }
            break;
        case BankCardFrontBTag:{
            self.BankCardFrontImage = [imageData base64EncodedString];
//            self.BankCardFrontImage = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        }
            break;
        case IDCardAndBankCardBTag:{
            self.IDCardAndBankCardImage = [imageData base64EncodedString];
//            self.IDCardAndBankCardImage = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        }
            break;
        default:
            break;
    }
}

//重新绘制图片的尺寸
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return scaledImage;
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    
    return self.titleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    InfoCertificationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InfoCertificationCell"];
    
    cell.titleL.text = self.titleArray[indexPath.row];
    cell.contentTF.placeholder = self.placeholderArray[indexPath.row];
    
    cell.contentTF.delegate = self;

#if SHOW_WEIZHUAN == 1
    if (indexPath.row == 2 || indexPath.row == 4) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    if (indexPath.row == 0) {
        cell.contentTF.text = self.realName;
    } else if (indexPath.row == 1) {
        cell.contentTF.text = self.IDNumber;
    } else if (indexPath.row == 2) {
        cell.contentTF.text = self.cardName;
    } else if (indexPath.row == 3) {
        cell.contentTF.text = self.cardNo;
    } else {
        if (self.province && self.city && self.area) {
            cell.contentTF.text = [NSString stringWithFormat:@"%@ %@ %@", self.province.provName, self.city.cityName, self.area.areaName];
        } else {
            cell.contentTF.text = @"";
        }
    }
#else
    if (indexPath.row == 3 || indexPath.row == 5) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    if (indexPath.row == 0) {
        cell.contentTF.text = self.activeCode;
    } else if (indexPath.row == 1) {
        cell.contentTF.text = self.realName;
    } else if (indexPath.row == 2) {
        cell.contentTF.text = self.IDNumber;
    } else if (indexPath.row == 3) {
        cell.contentTF.text = self.cardName;
    } else if (indexPath.row == 4) {
        cell.contentTF.text = self.cardNo;
    } else {
        if (self.province && self.city && self.area) {
            cell.contentTF.text = [NSString stringWithFormat:@"%@ %@ %@", self.province.provName, self.city.cityName, self.area.areaName];
        } else {
            cell.contentTF.text = @"";
        }
    }
#endif
    
    return cell;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
#if SHOW_WEIZHUAN == 1
    if ([textField.placeholder isEqualToString:self.placeholderArray[0]] ||
        [textField.placeholder isEqualToString:self.placeholderArray[1]] ||
        [textField.placeholder isEqualToString:self.placeholderArray[3]]) {
        return YES;
    }
#else 
    if ([textField.placeholder isEqualToString:self.placeholderArray[0]] ||
        [textField.placeholder isEqualToString:self.placeholderArray[1]] ||
        [textField.placeholder isEqualToString:self.placeholderArray[2]] ||
        [textField.placeholder isEqualToString:self.placeholderArray[4]]) {
        return YES;
    }
#endif
    
    [self.view endEditing:YES];
#if SHOW_WEIZHUAN == 1
    if ([textField.placeholder isEqualToString:self.placeholderArray[4]]) {
#else
    if ([textField.placeholder isEqualToString:self.placeholderArray[5]]) {
#endif
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [TDHttpEngine requestForGetProvinceWithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] complete:^(BOOL succeed, NSString *msg, NSString *cod, NSArray *array) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            if (succeed) {
                TDSelectLocationTableViewController *controller = [[TDSelectLocationTableViewController alloc] initWithStyle:UITableViewStylePlain];
                controller.locations = array;
                controller.complete = ^(TDProvince *province, TDCity *city, TDArea *area) {
                    self.province = province;
                    self.city = city;
                    self.area = area;
                    
                    [self.tableView reloadData];
                };
                
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
                nav.navigationBar.barTintColor = NavigatorBackgroundColor;
                nav.navigationBar.tintColor = [UIColor whiteColor];
                nav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
                [self presentViewController:nav animated:YES completion:nil];
            } else {
                [self.view makeToast:msg duration:2.0f position:@"center"];
            }
        }];
    } else {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [TDHttpEngine requestFor_GETBANKNAME_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] complete:^(BOOL succeed, NSString *msg, id reqBody) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            if (succeed) {
                NSArray *bankList = [reqBody objectForKey:@"dictList"];
                
                TDSelectBankNameTableViewController *controller = [[TDSelectBankNameTableViewController alloc] initWithStyle:UITableViewStylePlain];
                controller.bankNameArray = bankList;
                controller.complete = ^(NSDictionary *bankInfo) {
                    
                    self.cardName = [bankInfo objectForKey:@"dictName"];
                    
                    [self.tableView reloadData];
                };
                
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
                nav.navigationBar.barTintColor = NavigatorBackgroundColor;
                nav.navigationBar.tintColor = [UIColor whiteColor];
                nav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
                [self presentViewController:nav animated:YES completion:nil];
            } else {
                [self.view makeToast:msg duration:2.0f position:@"center"];
            }
        }];
    }
    
    return NO;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *content = [textField.text stringByReplacingCharactersInRange:range withString:string];
#if SHOW_WEIZHUAN == 1
    if ([textField.placeholder isEqualToString:self.placeholderArray[0]]) {
        self.realName = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[1]]) {
        self.IDNumber = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[3]]) {
        self.cardNo = content;
    }
#else
    if ([textField.placeholder isEqualToString:self.placeholderArray[0]]) {
        self.activeCode = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[1]]) {
        self.realName = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[2]]) {
        self.IDNumber = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[4]]) {
        self.cardNo = content;
    }
#endif
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSString *content = textField.text;
#if SHOW_WEIZHUAN == 1
    if ([textField.placeholder isEqualToString:self.placeholderArray[0]]) {
        self.realName = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[1]]) {
        self.IDNumber = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[3]]) {
        self.cardNo = content;
    }
#else
    if ([textField.placeholder isEqualToString:self.placeholderArray[0]]) {
        self.activeCode = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[1]]) {
        self.realName = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[2]]) {
        self.IDNumber = content;
    } else if ([textField.placeholder isEqualToString:self.placeholderArray[4]]) {
        self.cardNo = content;
    }
#endif
    
    return YES;
}

@end
